{% extends "base.html" %}

{% block title %}XBot管理后台 - 仪表盘{% endblock %}

{% block page_title_icon %}<i class="bi bi-speedometer2 page-title-icon"></i>{% endblock %}
{% block page_title %}仪表盘{% endblock %}

{% block content %}
<!-- 系统状态卡片组 -->
<div class="row mb-4">
    <!-- XBot状态卡片 -->
    <div class="col-md-6 col-lg-3 mb-3">
        <div class="card status-card">
            <div class="card-body d-flex align-items-center p-3">
                <div class="flex-shrink-0 icon-wrapper bg-primary-light">
                    <i class="bi bi-robot text-primary"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">XBot状态</div>
                    <div class="fw-bold d-flex align-items-center">
                            <span class="status-indicator status-online"></span>
                            运行中
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 微信状态卡片 -->
    <div class="col-md-6 col-lg-3 mb-3">
        <div class="card status-card">
            <div class="card-body d-flex align-items-center p-3">
                <div class="flex-shrink-0 icon-wrapper bg-success-light">
                    <i class="bi bi-chat-dots text-success"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">微信状态</div>
                    <div class="fw-bold d-flex align-items-center" id="dashboardWechatStatus">
                            <span class="status-indicator status-offline"></span>
                            未登录
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 插件状态卡片 -->
    <div class="col-md-6 col-lg-3 mb-3">
        <div class="card status-card">
            <div class="card-body d-flex align-items-center p-3">
                <div class="flex-shrink-0 icon-wrapper bg-warning-light">
                    <i class="bi bi-puzzle text-warning"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">已加载插件</div>
                    <div class="fw-bold" id="pluginCount">0</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 消息统计卡片 -->
    <div class="col-md-6 col-lg-3 mb-3">
        <div class="card status-card">
            <div class="card-body d-flex align-items-center p-3">
                <div class="flex-shrink-0 icon-wrapper bg-info-light">
                    <i class="bi bi-envelope text-info"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">今日消息</div>
                    <div class="fw-bold" id="todayMessages">--</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 统计图表 -->
<div class="row mb-4">
    <!-- 消息统计图表 -->
    <div class="col-lg-8 mb-3">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">消息统计</h5>
                <div class="card-actions">
                    <button class="btn btn-sm btn-outline-secondary" onclick="reloadCharts()">
                        <i class="bi bi-arrow-repeat"></i> 刷新
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="chart-container" style="height: 300px;">
                    <canvas id="messageStatsChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 系统资源监控 -->
    <div class="col-lg-4 mb-3">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">系统资源</h5>
            </div>
            <div class="card-body">
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="small text-muted">CPU使用率</div>
                        <div class="fw-bold" id="cpuUsageText">--</div>
                    </div>
                    <div class="progress" style="height: 8px;">
                        <div id="cpuUsageBar" class="progress-bar bg-success" style="width: 0%"></div>
                    </div>
                </div>
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="small text-muted">内存使用率</div>
                        <div class="fw-bold" id="memoryUsageText">--</div>
                    </div>
                    <div class="progress" style="height: 8px;">
                        <div id="memoryUsageBar" class="progress-bar bg-primary" style="width: 0%"></div>
                    </div>
                </div>
                <div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="small text-muted">磁盘使用率</div>
                        <div class="fw-bold" id="diskUsageText">--</div>
                    </div>
                    <div class="progress" style="height: 8px;">
                        <div id="diskUsageBar" class="progress-bar bg-warning" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 微信登录和最近消息 -->
<div class="row">
    <!-- 微信登录区域 -->
    <div class="col-lg-5 mb-3">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">微信登录</h5>
                <div class="card-actions">
                    <button class="btn btn-sm btn-primary" onclick="getWechatQRCode()">
                        <i class="bi bi-qr-code"></i> 获取二维码
                    </button>
                    <button class="btn btn-sm btn-outline-secondary ms-2" onclick="checkWechatStatus()">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="wechatLoginArea" class="text-center py-3">
                    <div class="wechat-login-status mb-3">
                        <span class="status-text fw-bold">请点击"获取二维码"按钮开始登录</span>
                    </div>
                    <div class="qrcode-container" id="qrcodeContainer">
                        <div class="wechat-tips">
                            <i class="bi bi-phone fs-1 text-muted mb-3"></i>
                            <p class="text-muted">请使用手机微信扫描二维码登录</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

    <!-- 最近消息列表 -->
    <div class="col-lg-7 mb-3">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">最近消息</h5>
                <div class="card-actions">
                    <button class="btn btn-sm btn-outline-secondary" onclick="loadRecentMessages()">
                        <i class="bi bi-arrow-repeat"></i> 刷新
                    </button>
    </div>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush" id="recentMessagesList">
                    <div class="text-center py-4 text-muted">
                        <div class="spinner-border spinner-border-sm" role="status"></div>
                        <p class="mt-2">加载中...</p>
        </div>
    </div>
            </div>
        </div>
    </div>
</div>

<!-- 增加底部样式 -->
<style>
.icon-wrapper {
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 1.5rem;
}

.bg-primary-light {
    background-color: rgba(67, 97, 238, 0.1);
}

.bg-success-light {
    background-color: rgba(16, 185, 129, 0.1);
}

.bg-warning-light {
    background-color: rgba(245, 158, 11, 0.1);
}

.bg-info-light {
    background-color: rgba(59, 130, 246, 0.1);
}

.status-card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.status-card:hover {
    transform: translateY(-5px);
}

.qrcode-container {
    min-height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed rgba(0,0,0,0.1);
    border-radius: 8px;
    margin: 0 auto;
    max-width: 250px;
}

.wechat-tips {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 2rem;
}
</style>

<!-- 图表和数据处理 -->
{% block scripts %}
<script src="{{ url_for('static', filename='js/chart.min.js') }}"></script>
<script>
// 全局变量
let messageChart = null;

// 页面加载时初始化仪表盘数据
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    setupCharts();
    loadRecentMessages();
    
    // 每30秒刷新一次数据
    setInterval(loadDashboardData, 30000);
    
    // 每2分钟刷新一次图表
    setInterval(updateCharts, 120000);
});

// 加载仪表盘数据
async function loadDashboardData() {
    try {
        // 加载系统状态
        const systemResponse = await fetch('/api/system/status');
        const systemData = await systemResponse.json();
            
        if (systemData.success) {
            // 更新系统资源信息
            updateSystemResources(systemData.data);
            
            // 更新插件计数
            document.getElementById('pluginCount').textContent = systemData.data.plugin_count || 0;
            
            // 更新微信状态
            if (systemData.data.wechat_status) {
                document.getElementById('dashboardWechatStatus').innerHTML = 
                    '<span class="status-indicator status-online"></span>已登录';
                
                document.querySelector('#wechatLoginArea .status-text').textContent = '微信已登录';
                document.querySelector('#qrcodeContainer').innerHTML = 
                    '<div class="text-success"><i class="bi bi-check-circle fs-1 mb-3"></i><p>微信已成功登录</p></div>';
            }
        }
        
        // 加载消息统计
        const statsResponse = await fetch('/api/chat/statistics');
        const statsData = await statsResponse.json();
        
        if (statsData.success) {
            document.getElementById('todayMessages').textContent = statsData.data.today_messages || 0;
        }
        
    } catch (error) {
        console.error('加载仪表盘数据失败:', error);
    }
}

// 更新系统资源显示
function updateSystemResources(data) {
    // CPU 使用率
    const cpuUsage = data.cpu_usage || 0;
    document.getElementById('cpuUsageText').textContent = cpuUsage + '%';
    document.getElementById('cpuUsageBar').style.width = cpuUsage + '%';
    
    if (cpuUsage > 80) {
        document.getElementById('cpuUsageBar').className = 'progress-bar bg-danger';
    } else if (cpuUsage > 50) {
        document.getElementById('cpuUsageBar').className = 'progress-bar bg-warning';
    } else {
        document.getElementById('cpuUsageBar').className = 'progress-bar bg-success';
    }
    
    // 内存使用率
    const memoryUsage = data.memory_usage || 0;
    document.getElementById('memoryUsageText').textContent = memoryUsage + '%';
    document.getElementById('memoryUsageBar').style.width = memoryUsage + '%';
    
    if (memoryUsage > 80) {
        document.getElementById('memoryUsageBar').className = 'progress-bar bg-danger';
    } else if (memoryUsage > 50) {
        document.getElementById('memoryUsageBar').className = 'progress-bar bg-warning';
    } else {
        document.getElementById('memoryUsageBar').className = 'progress-bar bg-primary';
    }
    
    // 磁盘使用率
    const diskUsage = data.disk_usage || 0;
    document.getElementById('diskUsageText').textContent = diskUsage + '%';
    document.getElementById('diskUsageBar').style.width = diskUsage + '%';
    
    if (diskUsage > 80) {
        document.getElementById('diskUsageBar').className = 'progress-bar bg-danger';
    } else if (diskUsage > 50) {
        document.getElementById('diskUsageBar').className = 'progress-bar bg-warning';
    } else {
        document.getElementById('diskUsageBar').className = 'progress-bar bg-info';
    }
}

// 设置图表
function setupCharts() {
    const ctx = document.getElementById('messageStatsChart').getContext('2d');
    
    // 创建图表
    messageChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [], // 将由数据填充
            datasets: [
                {
                    label: '私聊消息',
                    data: [],
                    fill: false,
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    pointRadius: 4,
                    pointBackgroundColor: 'rgb(59, 130, 246)'
                },
                {
                    label: '群聊消息',
                    data: [],
                    fill: false,
                    borderColor: 'rgb(16, 185, 129)',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    tension: 0.4,
                    pointRadius: 4,
                    pointBackgroundColor: 'rgb(16, 185, 129)'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                }
            }
        }
    });
    
    // 初始化图表数据
    updateCharts();
}

// 更新图表数据
async function updateCharts() {
    try {
        const response = await fetch('/api/chat/history/stats');
        const data = await response.json();
        
        if (data.success && data.data) {
            const chartData = data.data;
            
            // 更新图表数据
            messageChart.data.labels = chartData.labels || [];
            messageChart.data.datasets[0].data = chartData.private_messages || [];
            messageChart.data.datasets[1].data = chartData.group_messages || [];
            messageChart.update();
        }
    } catch (error) {
        console.error('更新图表数据失败:', error);
    }
}

// 重新加载图表
function reloadCharts() {
    updateCharts();
}

// 获取微信二维码
async function getWechatQRCode() {
    const qrcodeContainer = document.getElementById('qrcodeContainer');
    qrcodeContainer.innerHTML = '<div class="spinner-border text-primary" role="status"></div><p class="mt-3">获取二维码中...</p>';
    
    try {
        const response = await fetch('/api/wechat/qrcode');
        const data = await response.json();
        
        if (data.success && data.data) {
            if (data.data.is_logged_in) {
                document.querySelector('#wechatLoginArea .status-text').textContent = '微信已登录';
                qrcodeContainer.innerHTML = '<div class="text-success"><i class="bi bi-check-circle fs-1 mb-3"></i><p>微信已成功登录</p></div>';
            } else {
                document.querySelector('#wechatLoginArea .status-text').textContent = '请扫描二维码登录';
                qrcodeContainer.innerHTML = `
                    <img src="${data.data.qr_code}" alt="微信登录二维码" class="img-fluid">
                    <p class="text-muted mt-2 small">二维码有效期: ${data.data.expires_in}秒</p>
                `;
                
                // 开始轮询检查登录状态
                startQRCodePolling(data.data.uuid);
            }
        } else {
            qrcodeContainer.innerHTML = `
                <div class="text-danger">
                    <i class="bi bi-exclamation-circle fs-1 mb-3"></i>
                    <p>获取二维码失败</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('获取微信二维码失败:', error);
        qrcodeContainer.innerHTML = `
            <div class="text-danger">
                <i class="bi bi-exclamation-circle fs-1 mb-3"></i>
                <p>获取二维码失败: ${error.message}</p>
            </div>
        `;
    }
}

// 轮询检查二维码状态
function startQRCodePolling(uuid) {
    const intervalId = setInterval(async () => {
        try {
            const response = await fetch(`/api/wechat/check?uuid=${uuid}`);
            const data = await response.json();
            
            if (data.success && data.data) {
                if (data.data.is_logged_in) {
                    clearInterval(intervalId);
                    document.querySelector('#wechatLoginArea .status-text').textContent = '微信已登录';
                    document.getElementById('qrcodeContainer').innerHTML = `
                        <div class="text-success">
                            <i class="bi bi-check-circle fs-1 mb-3"></i>
                            <p>微信已成功登录</p>
                        </div>
                    `;
                    
                    // 更新仪表盘上的微信状态
                    document.getElementById('dashboardWechatStatus').innerHTML = 
                        '<span class="status-indicator status-online"></span>已登录';
                    
                    // 刷新数据
                    loadDashboardData();
                    loadRecentMessages();
                }
            }
        } catch (error) {
            console.error('检查二维码状态失败:', error);
        }
    }, 3000);
    
    // 60秒后自动停止轮询
    setTimeout(() => {
        clearInterval(intervalId);
    }, 60000);
}

// 加载最近消息
async function loadRecentMessages() {
    const messagesList = document.getElementById('recentMessagesList');
    messagesList.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
            <p class="mt-2 text-muted">正在加载最近消息...</p>
        </div>
    `;
    
    try {
        const response = await fetch('/api/chat/recent?limit=5');
        const data = await response.json();
        
        if (data.success && data.data) {
            const messages = data.data;
            
            if (messages.length === 0) {
                messagesList.innerHTML = `
                    <div class="text-center py-4">
                        <i class="bi bi-inbox fs-3 text-muted"></i>
                        <p class="text-muted">暂无最近消息</p>
                    </div>
                `;
        return;
    }
    
            let html = '';
            messages.forEach(msg => {
                const time = new Date(msg.timestamp).toLocaleString();
                const displayName = msg.sender_name || msg.sender_wxid || '未知用户';
                const content = formatMessageContent(msg);
                
                html += `
                    <div class="list-group-item">
                        <div class="d-flex align-items-center">
                            <div class="flex-shrink-0 me-3">
                                <div class="avatar ${msg.chat_type === 'group' ? 'bg-success' : 'bg-primary'}">
                                    ${displayName[0].toUpperCase()}
                                </div>
                                        </div>
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between">
                                    <h6 class="mb-0">${displayName}</h6>
                                    <small class="text-muted">${time}</small>
                                </div>
                                <div class="message-preview">${content}</div>
                                ${msg.chat_type === 'group' ? `<small class="text-muted">群组: ${msg.chat_name || msg.chat_id}</small>` : ''}
                            </div>
                        </div>
                    </div>
                `;
            });
            
            messagesList.innerHTML = html;
        } else {
            messagesList.innerHTML = `
                <div class="text-center py-4">
                    <i class="bi bi-exclamation-circle fs-3 text-muted"></i>
                    <p class="text-muted">加载失败，请稍后重试</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载最近消息失败:', error);
        messagesList.innerHTML = `
            <div class="text-center py-4">
                <i class="bi bi-exclamation-circle fs-3 text-muted"></i>
                <p class="text-muted">加载失败: ${error.message}</p>
            </div>
        `;
    }
}

// 格式化消息内容
function formatMessageContent(msg) {
    const content = msg.content || '';
    const msgType = msg.msg_type || 1;
    
    switch (msgType) {
        case 1: // 文本
            return escapeHtml(content).length > 50 
                ? escapeHtml(content).substring(0, 50) + '...' 
                : escapeHtml(content);
        case 3: // 图片
            return '<span class="text-muted"><i class="bi bi-image"></i> [图片消息]</span>';
        case 34: // 语音
            return '<span class="text-muted"><i class="bi bi-mic"></i> [语音消息]</span>';
        case 43: // 视频
            return '<span class="text-muted"><i class="bi bi-camera-video"></i> [视频消息]</span>';
        case 47: // 表情
            return '<span class="text-muted"><i class="bi bi-emoji-smile"></i> [表情消息]</span>';
        default:
            return '<span class="text-muted">[未知类型消息]</span>';
    }
}

// 转义HTML
function escapeHtml(text) {
    if (!text) return '';
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
</script>

<style>
.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    color: white;
}

.message-preview {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #6c757d;
    font-size: 0.875rem;
}

.list-group-item {
    transition: all 0.2s ease;
}

.list-group-item:hover {
    background-color: rgba(0, 0, 0, 0.02);
}
</style>
{% endblock %}
{% endblock %} 